package com.hxzy.common.util;

import lombok.extern.log4j.Log4j2;

import javax.servlet.ServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Log4j2
public class HttpHelper {

    /**
     * 读取ServletReuqest中的流，把为字符串
     * @param request
     * @return
     */
    public static String getBodyString(ServletRequest request)
    {
        StringBuilder sb = new StringBuilder();
        //构一个字符缓存流，加快读取速度
        BufferedReader reader = null;
        //得到请求中的 字节流byte[]
        try (InputStream inputStream = request.getInputStream())
        {
            //为了解决byte[]字节流中的中文乱码的问题，搞了一个包装流，  把字节流 转换成  字符流
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
        }
        catch (IOException e)
        {
            log.warn("getBodyString出现问题！");
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    log.error(e.getMessage());
                }
            }
        }
        return sb.toString();
    }
}
